//
//  WBRefreshControl.swift
//  sinazd
//
//  Created by apple on 16/3/14.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
private let RefreshHeight:CGFloat = 60

enum WBRefreshStatus:Int{
    
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
    
}

class WBRefreshControl: UIControl {
    
    var statue:WBRefreshStatus = .Normal {
        
        didSet{
            
            switch statue{
                
            case .Normal:
                print("下拉刷新")
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowIcon.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        
                        if oldValue == .Refreshing {
                            
                            var inset = self.scrowview!.contentInset
                            inset.top -= RefreshHeight
                            self.scrowview?.contentInset = inset
                            
                            self.indicationView.stopAnimating()
                            
                            
                            self.tipLabel.text = "下拉刷新"
                            self.arrowIcon.hidden = false
                        }
                        
                })
                
             
            case .Pulling:
                print("松手刷新")
                tipLabel.text = "松手刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
                
            case .Refreshing:
                print("正在刷新")
                tipLabel.text = "正在刷新"
                arrowIcon.hidden = true
                
                indicationView.startAnimating()
                
                self.sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
            
                    var inset = self.scrowview!.contentInset
                    
                    inset.top += RefreshHeight
                    
                    self.scrowview?.contentInset = inset
                    
                    
                })
                
            }
            
        }

}
    
    
    func endRefreshing() {
        
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1))
        
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            
            self.statue = .Normal
      
        }
        
    }
    
    
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshHeight, width: ScreenWidth, height: RefreshHeight)
        super.init(frame: rect)
        
        backgroundColor = UIColor.greenColor()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let offsetY = scrowview?.contentOffset.y ?? 0
        
        if scrowview!.dragging {
           
            
            
            if statue == .Pulling && offsetY > -124 {
                
                statue = .Normal
                
            }else if statue == .Normal && offsetY < -124{
                
                statue = .Pulling
                
            }
            
        }else{
            
            if statue == .Pulling {
                statue = .Refreshing
            }
        }
        
    }
    
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        if let myFatherView = newSuperview as? UIScrollView {
            
            scrowview = myFatherView
            
            scrowview?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
        
    }
    
    deinit {
        
        scrowview?.removeObserver(self, forKeyPath: "contentOffset")
        
    }
    
    
    
    
    private var scrowview:UIScrollView?
    
    
    private func setupUI() {
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
        
        backImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
        }
        
        //设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
    }
    
    
    
    //MARK: 懒加载子视图
    private lazy var tipLabel: UILabel = UIFactory.labelWith("下拉刷新", textColor: UIColor.darkGrayColor(), fontSize: 14)
    
    //箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //小菊花
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    

}
